/*
 * startup_module.c
 *
 *  Created on: 2020-12-28
 *      Author: chenss
 */

#include "module.h"
#include <string.h>

/* start address for the initialization values of the .data section.
defined in linker script */
extern unsigned int  _sidata;
/* start address for the .data section. defined in linker script */
extern unsigned int  _sdata;
/* end address for the .data section. defined in linker script */
extern unsigned int  _edata;
/* start address for the .bss section. defined in linker script */
extern unsigned int  _sbss;
/* end address for the .bss section. defined in linker script */
extern unsigned int  _ebss;

extern void Module_GetModuleVector(Module_Vector_t *module);
void Module_SetAppVector(const APP_Vector_t *app);


static inline void __attribute__((always_inline)) _initialize_data(unsigned int *from, unsigned int *start, unsigned int *end)
{
    // Iterate and copy word by word.
    // It is assumed that the pointers are word aligned.
    unsigned int *p = start;

    while(p < end)
    {
        *p++ = *from++;
    }
}

static inline void __attribute__((always_inline)) _initialize_bss(unsigned int *start, unsigned int *end)
{
    // Iterate and clear word by word.
    // It is assumed that the pointers are word aligned.
    unsigned int *p = start;

    while(p < end)
    {
        *p++ = 0;
    }
}

void Reset_Handler(const APP_Vector_t *app, Module_Vector_t *module)
{

    _initialize_data(& _sidata, & _sdata, & _edata);
    _initialize_bss(& _sbss, & _ebss);

    Module_SetAppVector(app);
    Module_GetModuleVector(module);
}
